// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.server.service;

import java.util.List;
import net.taviscaron.drivenotes.server.model.dao.ChargingDAO;
import net.taviscaron.drivenotes.server.model.validators.Validator;
import net.taviscaron.drivenotes.server.util.EntityUtils;
import net.taviscaron.drivenotes.shared.exceptions.InvalidEntityException;
import net.taviscaron.drivenotes.shared.model.entity.Car;
import net.taviscaron.drivenotes.shared.model.entity.Charging;
import net.taviscaron.drivenotes.shared.service.ChargingService;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

/**
 * Charging service impl
 * @author Andrei Senchuk
 */
public class ChargingServiceImpl implements ChargingService {
    private Validator<Charging> chargingValidator;
    private ChargingDAO chargingDAO;

    @Required
    public void setChargingValidator(Validator<Charging> chargingValidator) {
        this.chargingValidator = chargingValidator;
    }

    @Required
    public void setChargingDAO(ChargingDAO chargingDAO) {
        this.chargingDAO = chargingDAO;
    }

    @Transactional
    public List<Charging> findChargingsByCar(Car car) {
        List<Charging> list = chargingDAO.findChargingsByCar(car);
        for(int i = 0; i < list.size(); i++) {
            list.set(i, EntityUtils.createChangringValueObject(list.get(i)));
        }
        return list;
    }

    @Transactional
    public void saveCharging(Charging service) throws InvalidEntityException {
        chargingValidator.validate(service);
        chargingDAO.save(service);
    }

    @Transactional
    public Charging findById(Long id) {
        Charging chargingObj = chargingDAO.findById(id);
        Charging charging = EntityUtils.createChangringValueObject(chargingObj);
        if(charging != null) {
            Car car = EntityUtils.createCarValueObject(chargingObj.getCar());
            car.setOwner(EntityUtils.createUserValueObject(chargingObj.getCar().getOwner()));
            charging.setCar(car);
        }
        return charging;
    }

    @Transactional
    public void removeChargingById(Long id) {
        Charging charging = chargingDAO.findById(id);
        chargingDAO.remove(charging);
    }
}
